// -----------------------------------------------------------------------
//  <copyright file="IdentityAppModule.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2024 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2024-04-15 16:36</last-date>
// -----------------------------------------------------------------------

using System.ComponentModel;

using DaprPlus.Builder;
using DaprPlus.Identity.Application.Identity.Roles.Seeds;
using DaprPlus.Identity.Application.Identity.Users.Seeds;
using DaprPlus.Identity.Domain.Services;

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;


namespace DaprPlus.Identity.Application;

[Description("Identity-应用模块")]
public class IdentityAppModule : MediatRModuleBase
{
    /// <summary>
    /// 获取 模块级别，级别越小越先启动
    /// </summary>
    public override ModuleLevel Level => ModuleLevel.Application;

    /// <summary>
    /// 将模块服务添加到依赖注入服务容器中
    /// </summary>
    /// <param name="services">依赖注入服务容器</param>
    /// <returns></returns>
    public override IServiceCollection AddServices(IServiceCollection services)
    {
        services.AddSingleton<IEntitySeeder, RoleSeeder>();
        services.AddSingleton<IEntitySeeder, UserSeeder>();

        services.AddHostedService<DataSyncService>();

        return base.AddServices(services);
    }

    private class DataSyncService(IServiceProvider provider) : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            await provider.ExecuteScopedWorkAsync(async sp =>
            {
                var service = sp.GetService<IRoleSyncService>();
                if (service != null)
                {
                    await service.Sync();
                }
            });
            await provider.ExecuteScopedWorkAsync(async sp =>
            {
                var service = sp.GetService<IUserSyncService>();
                if (service != null)
                {
                    await service.Sync();
                }
            });
        }
    }
}


